package com.example.demo.arithmetic.datastructure.linkedlist2;

import java.util.function.Consumer;

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode head = null;

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public ListNode(int val) {
        this.val = val;
    }

//    public static ListNode of(int[] elements) {
//        for (int element : elements) {
//            addNodeToTail()
//        }
//    }

    public void addFirst(int element) {
        // 链表为空
        //head = new Node(element, null);
        // 链表非空
        head = new ListNode(element, head);
    }

    public static ListNode addNodeToTail(ListNode head, int val) {
        // 如果链表为空，则新节点就是头节点
        if (head == null) {
            return new ListNode(val);
        }

        // 遍历链表找到最后一个节点
        ListNode current = head;
        while (current.next != null) {
            current = current.next;
        }

        // 在最后一个节点后面添加新节点
        current.next = new ListNode(val);

        // 返回头节点（对于非空链表，头节点不变）
        return head;
    }

    public void loop1() {
        ListNode p = head;
        while (p != null) {
            p = p.next;
        }
    }
}

